#!/bin/sh

# Create MaxScale user if it doesnt' exist
getent passwd maxscale > /dev/null
if [ $? -ne 0 ]
then
    groupadd -r maxscale
    useradd -r -s /bin/false -g maxscale maxscale
fi

# Change the owner of the directories to maxscale:maxscale
for path in "@DEFAULT_LOGDIR@" "@DEFAULT_DATADIR@" "@DEFAULT_CACHEDIR@" "@DEFAULT_PIDDIR@" "@DEFAULT_MODULE_CONFIGDIR@" "@DEFAULT_CONFIGSUBDIR@"
do
    chown -R maxscale:maxscale "$path"
    chmod 0755 "$path"
done

# Install ldconfig files
if [ -f "@DEFAULT_SHAREDIR@/maxscale.conf" ]
then
    cp @DEFAULT_SHAREDIR@/maxscale.conf /etc/ld.so.conf.d/
else
    echo "Could not find ldconfig file: @DEFAULT_SHAREDIR@/maxscale.conf" >& 2
fi

# Only copy the service files if the systemd folder and systemctl executable are found
if [ -f @DEFAULT_SHAREDIR@/maxscale.service ] && command -v systemctl >/dev/null
then
    if [ -d "/lib/systemd/system"  ]
    then
        cp @DEFAULT_SHAREDIR@/maxscale.service /lib/systemd/system
        systemctl daemon-reload
    elif [ -d "/usr/lib/systemd/system"  ]
    then
        cp @DEFAULT_SHAREDIR@/maxscale.service /usr/lib/systemd/system
        systemctl daemon-reload
    fi

    # Remove old directories, mistakenly installed by a few versions
    if [ -d /lib/systemd/system/maxscale.service.d ]
    then
        rmdir /lib/systemd/system/maxscale.service.d
    elif  [ -d /usr/lib/systemd/system/maxscale.service.d ]
    then
        rmdir /lib/systemd/system/maxscale.service.d
    fi

    systemctl enable maxscale.service > /dev/null

    systemctl is-active maxscale.service --quiet > /dev/null && systemctl restart maxscale.service > /dev/null
fi

# If no maxscale.cnf file is found in /etc, copy the template file there
if [ ! -f "@MAXSCALE_CONFDIR@/maxscale.cnf" ]
then
    cp @MAXSCALE_CONFDIR@/maxscale.cnf.template @MAXSCALE_CONFDIR@/maxscale.cnf
fi

# If no logrotate config file is found, create one
if [ ! -f "/etc/logrotate.d/maxscale_logrotate" ]
then
    cp @DEFAULT_SHAREDIR@/maxscale_logrotate /etc/logrotate.d/maxscale_logrotate
fi

/sbin/ldconfig
